//
//  ViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/15.
//

import UIKit
import MJRefresh

class LYEmohViewController: LYBaseViewController {
    
    private let scrollView = UIScrollView()
    private let contentView = UIView()
    
    let homeTopView = LYEmohTopView()
    let ourDataView = LYOurDataView()
    let guideView = LYLoanGuideView()
    let productListView = LYSmallCardListView()
    let repaymentCarouseView = LYRepaymentCarouseView()
    
    lazy var carouselView: LYLargeCardCarouseView = {

        let carouselView = LYLargeCardCarouseView()
        carouselView.delegate = self
        return carouselView
    }()
    
    var topReceiveer: Receiveer? = nil
    
    var homeListData: HomeListData? = nil
    
    var titleName: String? = nil
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(showLoginController(_:)), name: .NotLoginInNotificationKey, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(orderListFollow(_:)), name: .orderListFollowKey, object: nil)
        
        self.isHiddenCustomTabBar = false
        
        KeychainManager.shared.saveString(idfv, forKey: idfvKey)
        
        commonInitSubViews()

        fetchData()
        
        // google_market上报
        if LYUserDefaults.shared.getBool(forKey: homeGoogleMarketKey) == nil {
            LYTrackingManager.uploadGoogleMarketTracking()
            LYUserDefaults.shared.setBool(true, forKey: homeGoogleMarketKey)
        }
    }
    
    // 刷新列表
    func updateData() {
        LYHUDUtils.showLoading()
        self.scrollView.mj_header?.beginRefreshing()
    }

    func commonInitSubViews() {
        scrollView.isDirectionalLockEnabled = true
        scrollView.alwaysBounceVertical = true
        scrollView.alwaysBounceHorizontal = false
//        scrollView.backgroundColor = .green
        scrollView.showsVerticalScrollIndicator = false
        scrollView.isUserInteractionEnabled = true
        view.addSubview(scrollView)
//        contentView.backgroundColor = .red
        scrollView.addSubview(contentView)
        homeTopView.addTarget(self, action: #selector(clickTopView(_:)), for: .touchUpInside)
        contentView.addSubview(homeTopView)
        contentView.addSubview(ourDataView)
        contentView.addSubview(guideView)
        
        let images = [
            UIImage(named: "home_customer_cycle")!,
            UIImage(named: "home_tips_cycle")!
        ]
        carouselView.update(images: images)
        contentView.addSubview(carouselView)
        productListView.delegate = self
        contentView.addSubview(productListView)
        
        repaymentCarouseView.delegate = self
        contentView.addSubview(repaymentCarouseView)
        
        scrollView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let self = self else { return }
            fetchData()
        })
        
        if let header = scrollView.mj_header as? MJRefreshNormalHeader {
            header.setTitle("", for: .idle)
            header.setTitle("", for: .pulling)
            header.setTitle("", for: .refreshing)
            header.lastUpdatedTimeLabel?.isHidden = true
            header.stateLabel?.isHidden = true
        }
        
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalToSuperview().offset(-customTabBarHeight - bottomMargin - 5)
        }
        
        contentView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.width.equalTo(scrollView)
        }
        
        homeTopView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(13)
            make.leading.trailing.equalToSuperview().inset(16)
        }
    }
    
    func setSmallCard() {
        ourDataView.isHidden = true
        guideView.isHidden = true
        carouselView.isHidden = true
        productListView.isHidden = false
        repaymentCarouseView.isHidden = false
        
//        contentView.snp.remakeConstraints { make in
//            make.leading.trailing.equalTo(view)
//            make.top.equalToSuperview()
//            make.bottom.equalTo(view).offset(-customTabBarHeight - bottomMargin)
//        }
        
        repaymentCarouseView.snp.makeConstraints  { make in
            make.top.equalTo(homeTopView.snp.bottom)
            make.centerX.equalToSuperview()
            make.width.equalTo(SCREEN_WIDTH - 2 * 16)
            make.height.equalTo(0)
        }

        productListView.snp.makeConstraints { make in
            make.top.equalTo(repaymentCarouseView.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(self.productListView.getTableViewListHeight())
            make.bottom.equalTo(contentView)
        }
        
        self.view.layoutIfNeeded()
        scrollView.contentSize = contentView.frame.size
    }
    
    func setRepaymentDatas(repayments: [Receiveer]) {
      
        if !repaymentCarouseView.isHidden {
            repaymentCarouseView.isHidden = repayments.isEmpty
        }

        let width = SCREEN_WIDTH - 2 * 16
        let height = width * (79 / 336.0)
        if !repaymentCarouseView.isHidden {
            repaymentCarouseView.snp.updateConstraints { make in
                make.height.equalTo(height)
            }
        }
    }
    
    func setLargeCard() {
        if appCountryEnv == .indonesia {
            ourDataView.isHidden = true
            guideView.isHidden = true
            carouselView.isHidden = true
            productListView.isHidden = true
            repaymentCarouseView.isHidden = true
        } else {
            ourDataView.isHidden = false
            guideView.isHidden = false
            carouselView.isHidden = false
            productListView.isHidden = true
            repaymentCarouseView.isHidden = true
        }

        ourDataView.snp.makeConstraints { make in
            make.top.equalTo(homeTopView.snp.bottom)
            make.leading.trailing.equalToSuperview().inset(13)
        }
        
        guideView.snp.makeConstraints { make in
            make.top.equalTo(ourDataView.snp.bottom).offset(30)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        carouselView.snp.makeConstraints { make in
            make.top.equalTo(guideView.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(103)
            make.bottom.equalTo(contentView)
        }
        
        self.view.layoutIfNeeded()
        scrollView.contentSize = contentView.frame.size
    }
    
    func fetchData() {
//        LYHUDUtils.showLoading(LYlocalizedString("loading..."))
        LYStocksManager.fetchMotherling { [weak self] homeListData, msg, error in
            guard let self = self else { return }
            self.homeListData = homeListData
            if error == nil {

                if let septenier = homeListData?.septenier {
                    
                    var septenierModel: Septenier? = nil
                    if let largeModel = septenier.first(where: {
                        $0.storyitious == "cordit"
                    }) {
                        // 大卡位
                        print("找到 laps 数据: \(largeModel)")
                        self.setLargeCard()
                        septenierModel = largeModel
                    } else if let smallModel = septenier.first(where: {
                        $0.storyitious == "ruberamongcy"
                    }) {
                        // PRODUCT_LIST
                        if let productListModel = septenier.first(where: {
                            $0.storyitious == "scabrfier"
                        }) {
                            self.productListView.dataSource = productListModel.receiveer
                        }
                        self.setSmallCard()
                        septenierModel = smallModel
                    }
                    
                    if let corditModel = septenierModel {
                        
                        let receiveer = corditModel.receiveer.first
                        self.topReceiveer = receiveer
                        let title = receiveer?.argue ?? ""

                        let baseURL = receiveer?.juxtaette ?? ""
                        let queryString = NetworkManager.shared.commonParameters.toURLQueryString()
                        let imageUrl = "\(baseURL)?\(queryString)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                        self.homeTopView.updateDatas(maximumTitle: receiveer?.passerency ?? "",
                                                     maximumAmount: receiveer?.auctproof ?? "",
                                                     deadLine: receiveer?.billionuous ?? "",
                                                     rate: receiveer?.dexter ?? "",
                                                     applyTitle: receiveer?.menaciability ?? "")

                        loadImage(from: imageUrl ?? "") { [weak self] image in
                            guard let self = self else { return }
                            var itemImage: UIImage? = UIImage(named: "logo_icon")
                            if let image = image {
                                itemImage = image
                            }
                            changeNavigationItem(image: itemImage,
                                                 title: title)
                        }
//                        self.productListView.dataSource = corditModel.receiveer
                    }
                    
                    // 还款提醒
                    if let productListModel = septenier.first(where: {
                        $0.storyitious == "torquesque"
                    }) {
                        self.repaymentCarouseView.update(datas: productListModel.receiveer)
                        self.setRepaymentDatas(repayments: productListModel.receiveer)
                    } else {
                        self.setRepaymentDatas(repayments: [])
                    }

//                    // PRODUCT_LIST
//                    if let productListModel = septenier.first(where: {
//                        $0.storyitious == "scabrfier"
//                    }) {
//                        self.productListView.dataSource = productListModel.receiveer
//                    }
                }
                LYHUDUtils.hideHUD()
            } else {
                LYHUDUtils.showToast(msg)
            }
            self.scrollView.mj_header?.endRefreshing()
        }
    }
    
    func fetchApplyConfig(_ receiveer: Receiveer) {
        guard let productId = receiveer.patientable else { return }
        LYHUDUtils.showLoading()
        LYStocksManager.fetchProductApplyTo(productId: productId) { [weak self] applyData, msg, error in
            guard let self = self else { return }
            if error == nil {
                // 复贷
                if let leon = applyData?.leon {
                    self.showRepaymentAlertView(receiveer, leon: leon)
                } else if let url = applyData?.obsless,
                          !url.isEmpty { // 借款中
                    if url.hasPrefix("http") || url.hasPrefix("https") {
                        pushToWebViewController(url)
                    } else {
                        LYSchemeManager.shared.parser(url)
                    }
                } else {
                    self.pushToProductDetailVC(receiveer)
                }
                LYHUDUtils.hideHUD()
            } else {
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    @objc func leftButtonTapped() {
        
    }
    
    @objc func clickTopView(_ sender: UIControl) {
        guard let receiveer = topReceiveer else { return }
        startApply(receiveer)
    }
    
    func startApply(_ receiveer: Receiveer) {
        let locationManager = LYLocationManager.shared
        locationManager.requestLocationPermission { [weak self] isAccess in
            guard let self = self else { return }
            if appCountryEnv == .indonesia {
                guard isAccess else { return }
            }
            
            self.fetchApplyConfig(receiveer)

            // 上报位置信息
            locationManager.getFullLocationInfo { locationInfo in
                if let info = locationInfo {
                    LYTrackingManager.uploadLocationTracking(locationInfo: info)
                }
            }
            
            // 设备信息上报详细信息
            LYTrackingManager.uploadDeviceInfoTracking()
            
            if let startTime = LYUserDefaults.shared.getDouble(forKey: loginStartTimeKey),
               let endTime = LYUserDefaults.shared.getDouble(forKey: loginEndTimeKey) {
                LYTrackingManager.uploadRiskTracking(sceneType: .signIn,
                                                     productId: nil,
                                                     orderNum: nil,
                                                     startTimeStamp: startTime,
                                                     endTimeStamp: endTime)
            }
        }
    }
    
    func loadImage(from urlString: String, completion: @escaping (UIImage?) -> Void) {
        guard let url = URL(string: urlString) else {
            completion(nil)
            return
        }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else {
                completion(nil)
                return
            }
            
            DispatchQueue.main.async {
                let image = UIImage(data: data)
                completion(image)
            }
        }.resume()
    }
    
    func changeNavigationItem(image: UIImage?, title: String) {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            let leftButton = UIButton(type: .custom)
            leftButton.setImageAndTitle(image: image,
                                        title: title,
                                        spacing: 5.0)
            leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .bold)
            leftButton.addTarget(self,
                                 action: #selector(leftButtonTapped),
                                 for: .touchUpInside)
            leftButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
            leftButton.isUserInteractionEnabled = false
            navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        }
    }
    
    private var isPresentingLogin = false
}

extension LYEmohViewController: LYLargeCardCarouselViewDelegate {
    // 实现代理方法处理点击事件
    func carouselView(_ carouselView: LYLargeCardCarouseView, didSelectItemAt index: Int) {
        switch index {
        case 0:
            if let url = self.homeListData?.guttality?.nonagenent {
                pushToWebViewController(url)
            }
        case 1:
            let tipsVC = LYLoanTipsController()
            UIApplication.topViewController()?.navigationController?.pushViewController(tipsVC, animated: true)
        default:
            break
        }
    }
}

extension LYEmohViewController: LYRepaymentCarouselViewDelegate {
    func carouselView(_ carouselView: LYRepaymentCarouseView, didSelectItemAt index: Int, data: Receiveer) {
        if let url = data.obsless { // 借款中
            if url.hasPrefix("http") || url.hasPrefix("https") {
                self.pushToWebViewController(url)
            } else {
                LYSchemeManager.shared.parser(url)
            }
        }
    }
}

extension LYEmohViewController: LYSmallCardListViewDelegate {
    func smallCardList(view: LYSmallCardListView, didSelect receiveer: Receiveer) {
        
        startApply(receiveer)
    }
    
    // 复贷弹窗
    func showRepaymentAlertView(_ receiveer: Receiveer, leon: Leon) {
        guard let novenmost = leon.novenmost else { return }
        let alert = LYCustomAlertView(
            title: LYlocalizedString("ProductInfo"),
            message: LYlocalizedString("repayment_content")
        )
        
        for (index, config) in novenmost.enumerated() {
            var actionType: LYAlertActionType = .obvious
            if index == 0 {
                actionType = .unObvious
            }
            let button = LYCustomAlertViewAction.getButton(with: config.nomadid ?? "",
                                                            actionType: actionType)
            alert.addButton(button) {
                alert.hide { [weak self] in
                    guard let self = self,
                          let url = config.obsless else { return }
                    if url.hasPrefix("http") || url.hasPrefix("https") {
                        pushToWebViewController(url)
                    } else {
                        LYSchemeManager.shared.parser(url)
                    }
                }
            }
        }

        // 显示弹窗
        alert.show()
    }
    
    func pushToProductDetailVC(_ receiveer: Receiveer) {
        let detailVC = LYProductDetailViewController()
        detailVC.productId = receiveer.patientable
        UIApplication.topViewController()?.navigationController?.pushViewController(detailVC, animated: true)
    }
}

// 通知
extension LYEmohViewController {
    @objc func showLoginController(_ notif: Notification) {
        guard !isPresentingLogin,
              let topVC = UIApplication.topViewController() else { return }
        let loginVC = LYLoginViewController()
        LYUserConfig.shared.removeLoginConfig()
        isPresentingLogin = true
        loginVC.modalPresentationStyle = .fullScreen
        topVC.present(loginVC, animated: true) {
            self.isPresentingLogin = false
        }
    }
    
    @objc func orderListFollow(_ notification: Notification) {
        
        guard let userInfo = notification.userInfo,
              let onomit = userInfo["customData"] as? Onomit,
              let orderNum = userInfo["orderNum"] as? String else { return }
        fetchProductDetailData(onomit: onomit, orderNum: orderNum)
    }
    
    func pushToWebViewController(_ url: String, isFollowOrder: Bool = false) {
        let webviewVC = LYWebViewController()
        webviewVC.urlString = url
        webviewVC.isFollowOrder = isFollowOrder
        UIApplication.topViewController()?.navigationController?.pushViewController(webviewVC, animated: true)
    }
    
    func fetchProductDetailData(onomit: Onomit, orderNum: String) {
        guard let patientable = onomit.patientable,
              let productId = Int(patientable) else { return }
        LYHUDUtils.showLoading()
        LYStocksManager.fetchProductDetail(productId: productId) { [weak self] product, msg, error in
            guard let self = self else { return }
            if error == nil, let product = product {
                handleApplyAction(productData: product,
                                  onomit: onomit,
                                  orderNum: orderNum,
                                  productId: productId)
            } else {
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    func handleApplyAction(productData: ProductData, onomit: Onomit, orderNum: String, productId: Int) {
        guard let stly = productData.stly else {
            
            let startTimeStamp = Date().timeIntervalSince1970
            LYStocksManager.fetchFollowUpOnOrderNumber(onomit: onomit) { [weak self] orderFollowData, msg, error in
                guard let self = self else { return }
                if error == nil {
                    if let obsless = orderFollowData?.obsless {
                        self.pushToWebViewController(obsless, isFollowOrder: true)
                    }
                    
                    LYTrackingManager.uploadRiskTracking(sceneType: .startLoan,
                                                         productId: productId,
                                                         orderNum: orderNum,
                                                         startTimeStamp: startTimeStamp,
                                                         endTimeStamp: Date().timeIntervalSince1970)
                    LYHUDUtils.hideHUD()
                } else {
                    LYHUDUtils.showToast(msg)
                }
            }
            return
        }
        
        LYHUDUtils.hideHUD()
        
        guard let matrious = stly.matrious else {
            return
        }
        
        self.titleName = stly.cipitfication
        
        let scene = IdentifyScene(rawValue: matrious)
        switch scene {
        case .public:
            goToPublicVC(onomit: onomit, orderNum: orderNum, productId: productId)
        case .personal:
            goToPersonalVC(onomit: onomit, orderNum: orderNum, productId: productId)
        case .ext:
            goToExtVC(onomit: onomit, orderNum: orderNum, productId: productId)
        case .bank:
            goToBankVC(onomit: onomit, orderNum: orderNum, productId: productId)
        default:
            print("nil")
        }
    }
    
    func goToPublicVC(onomit: Onomit, orderNum: String, productId: Int) {
        let publicVC = LYPublicViewController()
        publicVC.productId = productId
        publicVC.orderNum = orderNum
        publicVC.onomit = onomit
        publicVC.titleName = titleName
        UIApplication.topViewController()?.navigationController?.pushViewController(publicVC, animated: true)
    }
    
    func goToPersonalVC(onomit: Onomit, orderNum: String, productId: Int) {
        let personalVC = LYPersonalViewController()
        personalVC.productId = productId
        personalVC.orderNum = orderNum
        personalVC.onomit = onomit
        personalVC.titleName = titleName
        UIApplication.topViewController()?.navigationController?.pushViewController(personalVC, animated: true)
    }
    
    func goToExtVC(onomit: Onomit, orderNum: String, productId: Int) {
        let extVC = LYExtViewController()
        extVC.productId = productId
        extVC.orderNum = orderNum
        extVC.onomit = onomit
        extVC.titleName = titleName
        UIApplication.topViewController()?.navigationController?.pushViewController(extVC, animated: true)
    }
    
    func goToBankVC(onomit: Onomit, orderNum: String, productId: Int) {
        let bankVC = LYBankViewController()
        bankVC.productId = productId
        bankVC.orderNum = orderNum
        bankVC.onomit = onomit
        bankVC.titleName = titleName
        UIApplication.topViewController()?.navigationController?.pushViewController(bankVC, animated: true)
    }
}
